package com.ly.algorithm.leetcode.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Classname Problem392
 * @Description
 *
 * 示例 1：
 *
 * 输入：s = "3[a]2[bc]"
 * 输出："aaabcbc"
 * 示例 2：
 *
 * 输入：s = "3[a2[c]]"
 * 输出："accaccacc"
 * 示例 3：
 *
 * 输入：s = "2[abc]3[cd]ef"
 * 输出："abcabccdcdcdef"
 * 示例 4：
 *
 * 输入：s = "abc3[cd]xyz"
 * 输出："abccdcdcdxyz"
 *
 *
 * @Date 2020/12/18 21:22
 * @Author 冷心影翼
 */
public class Problem392 {

	public static void main(String[] args) {
		Solution392 solution392 = new Solution392();
		System.out.println(solution392.decodeString("2[avb]"));
	}
}


class Solution392 {
	public String decodeString(String s) {
		char[] chars = s.toCharArray();
		Stack<Character> resStack = new Stack<>();
		Stack<Integer> helpStack = new Stack<>();
		String numStr = "";
		for(int i=0;i<chars.length;i++) {
			int num = chars[i] - '0';
			if (num >= 0 && num <= 9) {
				numStr += num;
				continue;
			}
			if(numStr != "") {
				helpStack.push(Integer.parseInt(numStr));
			}

			numStr = "";
			if(chars[i] == ']') {
				List<Character> list = new ArrayList<>();
				Character c;
				while ( (c = resStack.pop()) !='[') {
					list.add(c);
				}
				Integer pop = helpStack.pop();
				for(int j=0;j<pop;j++) {
					for(int k=list.size()-1;k>=0;k--) {
						resStack.push(list.get(k));
					}
				}
			}else {
				resStack.push(chars[i]);
			}
		}
		StringBuilder sb = new StringBuilder("");
		while (!resStack.isEmpty()) {
			sb.append(resStack.pop());
		}
		return sb.reverse().toString();
	}
}